import * as config from './config'
import axios from 'axios'

export function imageUrl(module) {
  return [
    config.HTTP_PROTOCOL,
    config.IMAGE_API_HOST,
    config.IMAGE_API_PREFIXES,
    module
  ].join('')
}

export function couponUrl(module) {
  return [
    config.HTTP_PROTOCOL,
    config.COUPON_API_HOST,
    config.COUPON_API_PREFIXES,
    module
  ].join('')
}

export function userUrl(module) {
  return [
    config.HTTP_PROTOCOL,
    config.USER_API_HOST,
    config.USER_API_PREFIXES,
    module
  ].join('')
}

export function mobileUrl(module) {
  return [
    config.HTTP_PROTOCOL,
    config.MOBILE_API_HOST,
    config.MOBILE_API_PREFIXES,
    module
  ].join('')
}

function checkHttpCode(res) {
  return res.status === 200 ? res.data : {}
}

function showNetWorkError(res) {
  console.log('NetWorkError', res)
  return Promise.resolve(res)
}

export function sendRequest(url, data, method) {
  if (!method) {
    method = 'get'
  }
  let sendConfig = {
    url: url,
    method: method,
    data: data
  }
  if (method === 'get') {
    sendConfig = Object.assign(sendConfig, {params: data, data: undefined})
  }
  if (method === 'post') {
    sendConfig = Object.assign(sendConfig, {
      transformRequest: [function (data) {
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  }
  return axios(sendConfig)
    .then(checkHttpCode)
    .then(res => {
      return Promise.resolve(res)
    }).catch(showNetWorkError)
}
